import { useEffect, useState } from 'react';
import { connect } from 'umi';
import { Link } from 'react-router-dom';
import type { ConnectRC, Tag } from 'umi';
import ProLayout from '@ant-design/pro-layout';
import { MenuUnfoldOutlined, MenuFoldOutlined } from '@ant-design/icons';
import type { BasicLayoutProps as ProLayoutProps } from '@ant-design/pro-layout';

import TabsView from '@/components/TabsView';
import RightContent from '@/components/RightContent';
import layoutDefaultSettings from '../../config/layoutDefaultSettings';

import './index.less';

interface LayoutsType extends ProLayoutProps {
  tagsModel: Tag[];
  loading: boolean;
}

const IndexPage: ConnectRC<LayoutsType> = (props) => {
  const [collapsed, setCollapsed] = useState(false);

  useEffect(() => {
    onresize = () => {
      const getOffsetWidth = document.body.offsetWidth;
      getOffsetWidth < 1000 && setCollapsed(true);
      getOffsetWidth > 1000 && setCollapsed(false);
    };
  }, []);

  // 获取选中的key
  const getActiveKey = (tags: Tag[]) => {
    return tags.filter((t) => t.active)[0].key;
  };

  return (
    <div
      id="test-pro-layout"
      style={{
        height: '100vh',
      }}
    >
      {!collapsed && document.body.offsetWidth <= 768  && (
        <div
          className="mask"
          onClick={() => {
            setCollapsed(!collapsed);
          }}
        />
      )}
      <ProLayout
        {...layoutDefaultSettings}
        collapsed={collapsed}
        menuHeaderRender={() => {
          return (
            <div
              className={`menu-logo ${collapsed ? 'closed' : 'open'} ${
                document.body.offsetWidth < 765 ? `hiddenLogo fix-header` : ''
              }`}
            >
            </div>
          );
        }}
        headerContentRender={() => {
          return (
            <div
              onClick={() => setCollapsed(!collapsed)}
              style={{
                width: '32px',
                cursor: 'pointer',
                fontSize: '16px',
              }}
            >
              {collapsed ? <MenuUnfoldOutlined /> : <MenuFoldOutlined />}
            </div>
          );
        }}
        menuItemRender={(menuItemProps, defaultDom) => {
          return <Link to={menuItemProps.path ?? '/'}>{defaultDom}</Link>;
        }}
        rightContentRender={() => <RightContent/>}
        route={props.route}
      >
        <div id="myWrapperLoading">
          <TabsView
            activeKey={getActiveKey(props.tagsModel)}
            tags={props.tagsModel}
            route={props.route}
            dispatch={props.dispatch}
          />
        </div>
      </ProLayout>
    </div>
  );
};

export default connect(({ tagsModel }: { tagsModel: Tag[] }) => ({
  tagsModel,
}))(IndexPage);
